package com.jing.shop.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.jing.shop.domain.Result;
import com.jing.shop.domain.User;
import com.jing.shop.domain.vo.PmsProductAttrRelVO;
import io.swagger.annotations.Api;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Validated
@RestController
@RequestMapping("/api")
@Api(tags = "接口")
public class TestController {

    public static void main(String[] args) {
        String str = "[\n" +
                "\t{\n" +
                "\t\t\"cid\": 1,\n" +
                "\t\t\"attrName\": \"黑色\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"cid\": 2,\n" +
                "\t\t\"attrName\": \"M\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"cid\": 1,\n" +
                "\t\t\"attrName\": \"红色\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"cid\": 2,\n" +
                "\t\t\"attrName\": \"X\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"cid\": 3,\n" +
                "\t\t\"attrName\": \"男\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"cid\": 3,\n" +
                "\t\t\"attrName\": \"女\"\n" +
                "\t}\n" +
                "]";

        List<PmsProductAttrRelVO> relVos = JSONArray.parseArray(str, PmsProductAttrRelVO.class);

        Map<Long, List<PmsProductAttrRelVO>> groupedByCid = relVos.stream()
                .collect(Collectors.groupingBy(PmsProductAttrRelVO::getCid));

        List<String> descartes = descartes(new ArrayList<>(groupedByCid.values()));

        List<Map<Long, String>> collect = descartes.stream()
                .map(descarte -> {
                    String[] split = descarte.split("--");
                    return Arrays.stream(split)
                            .map(s -> JSONObject.parseObject(s, PmsProductAttrRelVO.class))
                            .collect(Collectors.toMap(PmsProductAttrRelVO::getCid, PmsProductAttrRelVO::getAttrName));
                })
                .collect(Collectors.toList());

        System.out.println(JSONObject.toJSONString(collect));
    }

    public static List<String> descartes(List<List<PmsProductAttrRelVO>> lists) {
        List<String> result = Lists.cartesianProduct(lists).stream()
                .map(lst -> lst.stream().map(JSONObject::toJSONString).collect(Collectors.joining("--")))
                .collect(Collectors.toList());
        return result;
    }



}
